<template>
  <el-dialog
    v-model="visible"
    title="设置教师"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-if="teachingMission" class="teacher-setup">
      <div class="mission-info">
        <h4>教学任务信息</h4>
        <p><strong>课程：</strong>{{ teachingMission.courseName }}</p>
        <p><strong>学期：</strong>{{ teachingMission.termName }}</p>
      </div>

      <el-divider />

      <div class="teacher-selection">
        <h4>选择教师</h4>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="available-teachers">
              <h5>可选教师</h5>
              <el-input
                v-model="searchKeyword"
                placeholder="搜索教师"
                prefix-icon="Search"
                style="margin-bottom: 10px"
              />
              <el-table
                :data="filteredAvailableTeachers"
                height="300"
                @row-click="addTeacher"
                style="cursor: pointer"
              >
                <el-table-column prop="name" label="姓名" />
                <el-table-column prop="username" label="用户名" />
                <el-table-column label="操作" width="60">
                  <template #default="scope">
                    <el-button
                      size="small"
                      type="primary"
                      :icon="Plus"
                      @click.stop="addTeacher(scope.row)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="selected-teachers">
              <h5>已选教师 <span class="drag-tip">(拖拽排序)</span></h5>
              <div class="teacher-list">
                <div v-if="selectedTeachers.length === 0" class="empty-teachers">
                  请从左侧选择教师
                </div>
                <draggable
                  v-model="selectedTeachers"
                  item-key="id"
                  @end="handleDragEnd"
                  :animation="200"
                  ghost-class="ghost"
                  chosen-class="chosen"
                  drag-class="drag"
                >
                  <template #item="{ element: teacher, index }">
                    <div class="teacher-item">
                      <div class="drag-handle">
                        <el-icon><More /></el-icon>
                      </div>
                      <div class="teacher-info">
                        <span class="teacher-name">{{ teacher.name }}</span>
                        <span class="teacher-username">({{ teacher.username }})</span>
                        <span class="sort-order">{{ index + 1 }}</span>
                      </div>
                      <div class="teacher-controls">
                        <el-checkbox
                          v-model="teacher.isPrimary"
                          @change="handlePrimaryChange(teacher, $event)"
                        >
                          主讲
                        </el-checkbox>
                        <el-button
                          size="small"
                          type="danger"
                          :icon="Delete"
                          @click="removeTeacher(index)"
                        />
                      </div>
                    </div>
                  </template>
                </draggable>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete, More } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { teachingMissionApi } from '@/api/teaching-mission'

export default {
  name: 'TeacherSetupDialog',
  components: {
    draggable,
    Plus,
    Delete,
    More
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    teachingMission: {
      type: Object,
      default: null
    },
    allTeachers: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:modelValue', 'success'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })

    const saving = ref(false)
    const searchKeyword = ref('')
    const selectedTeachers = ref([])

    // 计算可选教师列表（排除已选择的）
    const filteredAvailableTeachers = computed(() => {
      let teachers = props.allTeachers.filter(teacher => 
        !selectedTeachers.value.some(selected => selected.id === teacher.id)
      )

      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        teachers = teachers.filter(teacher =>
          teacher.name.toLowerCase().includes(keyword) ||
          teacher.username.toLowerCase().includes(keyword)
        )
      }

      return teachers
    })

    // 监听教学任务变化，加载当前教师
    watch(() => props.teachingMission, async (newMission) => {
      if (newMission && newMission.id) {
        await loadCurrentTeachers()
      }
    }, { immediate: true })

    // 加载当前教学任务的教师
    const loadCurrentTeachers = async () => {
      if (!props.teachingMission?.id) return

      try {
        const response = await teachingMissionApi.getTeachingMissionTeachers(props.teachingMission.id)
        selectedTeachers.value = response.map(teacher => ({
          id: teacher.teacherId,
          name: teacher.teacherName,
          username: teacher.teacherUsername || teacher.teacherName, // fallback
          sortOrder: teacher.sortOrder,
          isPrimary: teacher.isPrimary
        })).sort((a, b) => a.sortOrder - b.sortOrder)
      } catch (error) {
        console.error('加载教师列表失败:', error)
        ElMessage.error('加载教师列表失败')
        selectedTeachers.value = []
      }
    }

    // 添加教师
    const addTeacher = (teacher) => {
      if (selectedTeachers.value.some(t => t.id === teacher.id)) {
        ElMessage.warning('该教师已经添加')
        return
      }

      selectedTeachers.value.push({
        id: teacher.id,
        name: teacher.name,
        username: teacher.username,
        sortOrder: selectedTeachers.value.length + 1,
        isPrimary: selectedTeachers.value.length === 0 // 第一个教师默认为主讲
      })
    }

    // 移除教师
    const removeTeacher = (index) => {
      const removedTeacher = selectedTeachers.value[index]
      selectedTeachers.value.splice(index, 1)
      
      // 重新计算排序
      updateOrder()

      // 如果移除的是主讲教师，且还有其他教师，则设置第一个为主讲
      if (removedTeacher.isPrimary && selectedTeachers.value.length > 0) {
        selectedTeachers.value[0].isPrimary = true
      }
    }

    // 拖拽结束处理
    const handleDragEnd = () => {
      updateOrder()
    }

    // 更新排序
    const updateOrder = () => {
      selectedTeachers.value.forEach((teacher, index) => {
        teacher.sortOrder = index + 1
      })
    }    // 处理主讲教师变更
    const handlePrimaryChange = (teacher, value) => {
      if (!value) {
        // 取消主讲，检查是否还有其他主讲教师
        const primaryTeachers = selectedTeachers.value.filter(t => t.isPrimary && t.id !== teacher.id)
        if (primaryTeachers.length === 0) {
          ElMessage.warning('至少需要设置一位主讲教师')
          nextTick(() => {
            teacher.isPrimary = true
          })
        }
      }
    }

    // 保存设置
    const handleSave = async () => {
      if (selectedTeachers.value.length === 0) {
        ElMessage.error('请至少选择一位教师')
        return
      }

      // 验证是否有主讲教师
      const primaryTeachers = selectedTeachers.value.filter(t => t.isPrimary)
      if (primaryTeachers.length === 0) {
        ElMessage.error('请至少设置一位主讲教师')
        return
      }

      saving.value = true
      try {
        const teacherIds = selectedTeachers.value.map(t => t.id)
        const orders = selectedTeachers.value.map((t, index) => index + 1)
        const primaryFlags = selectedTeachers.value.map(t => t.isPrimary)

        await teachingMissionApi.reorderTeachers(
          props.teachingMission.id,
          teacherIds,
          orders,
          primaryFlags
        )

        ElMessage.success('教师设置保存成功')
        emit('success')
        handleClose()
      } catch (error) {
        console.error('保存教师设置失败:', error)
        ElMessage.error('保存教师设置失败')
      } finally {
        saving.value = false
      }
    }

    // 关闭对话框
    const handleClose = () => {
      selectedTeachers.value = []
      searchKeyword.value = ''
      emit('update:modelValue', false)
    }

    return {
      visible,
      saving,
      searchKeyword,
      selectedTeachers,
      filteredAvailableTeachers,
      addTeacher,
      removeTeacher,
      handleDragEnd,
      updateOrder,
      handlePrimaryChange,
      handleSave,
      handleClose,
      Plus,
      Delete,
      More
    }
  }
}
</script>

<style scoped>
.teacher-setup {
  min-height: 400px;
}

.mission-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.mission-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.mission-info p {
  margin: 5px 0;
  color: #606266;
}

.teacher-selection h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.teacher-selection h5 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.drag-tip {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.available-teachers,
.selected-teachers {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  height: 400px;
}

.teacher-list {
  max-height: 350px;
  overflow-y: auto;
}

.teacher-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.teacher-item:hover {
  background: #ecf5ff;
  border-color: #409eff;
}

.drag-handle {
  cursor: move;
  color: #909399;
  margin-right: 10px;
  display: flex;
  align-items: center;
  padding: 4px;
}

.drag-handle:hover {
  color: #409eff;
}

.teacher-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.teacher-name {
  font-weight: 500;
  color: #303133;
}

.teacher-username {
  color: #909399;
  font-size: 12px;
}

.sort-order {
  color: #409eff;
  font-size: 12px;
  font-weight: 500;
  background: #ecf5ff;
  padding: 2px 6px;
  border-radius: 10px;
  margin-left: auto;
  margin-right: 10px;
}

.teacher-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.empty-teachers {
  text-align: center;
  color: #909399;
  padding: 40px 0;
  font-style: italic;
}

/* 拖拽样式 */
.ghost {
  opacity: 0.5;
  background: #409eff;
  color: white;
}

.chosen {
  opacity: 0.8;
  transform: scale(1.02);
}

.drag {
  transform: rotate(5deg);
}

:deep(.el-table .el-table__row) {
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
